<?php

/**
 *    购物车控制器，负责会员购物车的管理工作，她与下一步售货员的接口是：购物车告诉售货员，我要买的商品是我购物车内的商品
 *
 *    @author    Garbin
 */

class CartApp extends MallbaseApp
{
	/**
     *    列出购物车中的商品
     *
     *    @author    Garbin
     *    @return    void
     */
	function index()
	{

		$this->_update_cart_status();//初始购物车状态

		$carts = $this->_get_cart_status();
		//print_r($carts);die();

		$this->_curlocal(
		LANG::get('cart')
		);
		$this->_config_seo('title', Lang::get('cart') . ' - ' . Conf::get('site_title'));

		//显示位置
		$shopcar_step = 'shopcar01';
		$this->assign('shopcar_step', $shopcar_step);

		if (empty($carts['carts']))
		{
			$this->_cart_empty();

			return;
		}

		$this->assign('carts', $carts['carts']);//购物车
		$this->assign('carts_status', $carts['status']);//购物车总状态
		$this->display('cart.index.html');
	}

	/**
     *    放入商品(根据不同的请求方式给出不同的返回结果)
     *
     *    @author    Garbin
     *    @return    void
     */
	function add()
	{
		$spec_quantity = str_replace('\\','',$_GET['spec_quantity']);
		$goods_id = isset($_GET['goods_id']) ? intval($_GET['goods_id']) : 0;
		$goods_price_type = isset($_GET['goods_price_type']) ? intval($_GET['goods_price_type']) : 1;
		$spec_quantity = ecm_json_decode($spec_quantity,1);
		$retval = array();
		$cart_item = array();
		$spec_id_arr = array();
		$quantity_arr = array();
		$goods_price = '0.00';
		$cart_model =& m('cart');
        $activity_goods_model =& m('activitygoods');
		if(!$spec_quantity && !$goods_id)
		{
			$this->json_error('no_such_goods');
			return;
		}
        $activity  = $activity_goods_model->_get_activity_goods($goods_id);//获取商品参与活动的数据
        $activity_goods = current($activity);


		foreach($spec_quantity as $key=>$val)
		{
			$spec_id   = isset($val['spec_id']) ? intval($val['spec_id']) : 0;
			$quantity   = isset($val['quantity']) ? intval($val['quantity']) : 0;
			if (!$spec_id || !$quantity)
			{
				$retval[$key]=$spec_id;
				continue;
			}
			/* 是否有商品 */
			$spec_model =& m('goodsspec');
			$spec_info  =  $spec_model->get(array(
			'fields'        => 'g.store_id, g.goods_id, g.goods_name, g.spec_name_1, g.spec_name_2, g.default_image,g.price_type, g.shipping_id ,g.gweight ,g.shipping_type,g.clearing_price,gs.spec_1, gs.spec_2, gs.stock, gs.price,gs.base_price',
			'conditions'    => $spec_id,
			'join'          => 'belongs_to_goods',
			));

			if (!$spec_info)
			{

				/* 商品不存在 */
				$retval[$key]=$spec_id;
				continue;
			}
			/* 如果是自己店铺的商品，则不能购买 */
			if ($this->visitor->get('manage_store'))
			{
				if ($spec_info['store_id'] == $this->visitor->get('manage_store'))
				{
					$this->json_error('can_not_buy_yourself');
					return;
				}
			}
			/* 是否添加过,如果有则数量相加,更新价格*/

			$item_info  = $cart_model->get("spec_id={$spec_id} AND session_id='" . SESS_ID . "'");

            if($activity_goods['discount_type'] == 1)
            {
                $price = $spec_info['price']*$activity_goods['promote_discount'];//优惠方式为打折
            }
            if($activity_goods['discount_type'] == 2)
            {
                $price = $activity_goods['promote_price'];//优惠方式为一口价
            }
            $goods_price = floatval($price) > 0 ? $price : $spec_info['price'];
            $shipping_id = $activity_goods['free_shipping'] == 1 ? 0 : $spec_info['shipping_id'];//限时包邮

			if (!empty($item_info))
			{
				$cart_model->edit("spec_id={$spec_id} AND session_id='" . SESS_ID . "'",array('price'=>$goods_price,'retail_price'=>$spec_info['price'],'shipping_id'=>$shipping_id,'quantity'=>$item_info['quantity']+$quantity));
				continue;
			}

			$spec_1 = $spec_info['spec_name_1'] ? $spec_info['spec_name_1'] . ':' . $spec_info['spec_1'] : $spec_info['spec_1'];
			$spec_2 = $spec_info['spec_name_2'] ? $spec_info['spec_name_2'] . ':' . $spec_info['spec_2'] : $spec_info['spec_2'];

			$specification = $spec_1 . ' ' . $spec_2;

			$base_price = $goods_price_type==1?$spec_info['clearing_price']:$spec_info['base_price'];//产品供货价

			/* 将商品加入购物车 */
			$cart_item[] = array(
			'user_id'       => $this->visitor->get('user_id'),
			'session_id'    => SESS_ID,
			'store_id'      => $spec_info['store_id'],
			'spec_id'       => $spec_id,
			'goods_id'      => $spec_info['goods_id'],
			'goods_name'    => addslashes($spec_info['goods_name']),
			'specification' => addslashes(trim($specification)),
			'shipping_id'   => $shipping_id,//运费模板
			'shipping_type' => intval($spec_info['shipping_type']),//运费类型
			'price'         => $goods_price,
			'base_price'    => $base_price,//供货价
			'quantity'      => $quantity,
			'goods_weight'  => $spec_info['gweight'],//商品重量
			'goods_image'   => addslashes($spec_info['default_image']),
			'price_type'    => $goods_price_type,
			'add_time'      =>  gmtime(),
			'retail_price'  =>  $spec_info['price'],
			);
		}

		if($retval)
		{
			$this->json_error('add_failure',$retval);
			return;
		}
		else
		{
			/* 统计信息，更新被添加进购物车的次数 */
			$model_goodsstatistics =& m('goodsstatistics');
			$model_goodsstatistics->edit($goods_id, 'carts=carts+1');

			/* 添加并返回购物车统计即可 */
			if($cart_item)
			{
				sort($cart_item);
				$cart_rs = $cart_model->add($cart_item);

				if (!$cart_rs)
				{
					$this->json_error('add_failure');
					return;
				}
			}

			/*如果是按数量报价的时候获取价格区间更新购物车里面的价格*/
			if($goods_price_type == 1)
			{
				$this->_update_cart_goods_price($goods_id);

			}
			$this->json_result('', 'addto_cart_successed');

		}


	}

	/**
     *    将商品添加到购物车成功后的页面
     *
     *    @author    yanghj 2014.7.10
     *    @return    void
     */
	function add_succeed()
	{
		$goods_id = isset($_GET['goods_id']) ? intval($_GET['goods_id']) : 0;
		$cate_id = isset($_GET['cate_id']) ? intval($_GET['cate_id']) : 0;
		if(!$goods_id || !$cate_id)
		{
			header("Location:index.php");
			exit;
		}
		$goods_mod =& m('goods');
		/*获取同一分类最新发布的商品*/
		$goods_list = $goods_mod->find(array(
		'conditions' => "closed = 0 AND if_show = 1 AND goods_id != ".$goods_id." AND cate_id = ".$cate_id,
		'fields'     => 'goods_name, default_image, price',
		'order'     => 'add_time DESC',
		'limit'      => 9,
		));
		/*如果没有商品则获取最新发布的商品*/
		if(!$goods_list)
		{
			$goods_list = $goods_mod->find(array(
			'conditions' => "closed = 0 AND if_show = 1 AND goods_id != ".$goods_id,
			'fields'     => 'goods_name, default_image, price',
			'order'     => 'add_time DESC',
			'limit'      => 9,
			));

		}
		if($goods_list)
		{
			foreach ($goods_list as $key => $goods)
			{
				empty($goods['default_image']) && $goods_list[$key]['default_image'] = Conf::get('default_goods_image');
			}
		}
		$this->assign('goods_list', $goods_list);//关联的商品
		$this->_config_seo('title', Lang::get('cart') . ' - ' . Conf::get('site_title'));
		$this->display('cart.succeed.html');
	}


	/**
     *    获取购物车状态
     *
     *    @author    Garbin
     *    @return    array
     */
	function _get_cart_status()
	{
		/* 默认的返回格式 */
		$data = array(
		'status'    =>  array(
		'quantity'  =>  0,      //总数量
		'amount'    =>  0,      //总金额
		'kinds'     =>  0,      //总种类
		),
		'carts'     =>  array(),    //购物车列表，包含每个购物车的状态
		);

		/* 获取所有购物车 */
		$carts = $this->_get_carts();
		if (empty($carts))
		{
			return $data;
		}
		$data['carts']  =   $carts;
		foreach ($carts as $store_id => $cart)
		{

			$data['status']['quantity'] += $cart['quantity'];
			$data['status']['amount']   += $cart['amount'];
			//	$data['status']['kinds']    += $cart['kinds'];

		}

		return $data;
	}

	/**
     *    购物车为空
     *
     *    @author    Garbin
     *    @return    void
     */
	function _cart_empty()
	{
		$this->display('cart.empty.html');
	}

	/**
     *    以店铺为单位获取购物车列表及商品项
     *
     *    @author    Garbin
     *    @return    void
     */
	function _get_carts()
	{
		$carts = array();

		/* 获取所有购物车中的内容 */

		/* 只有是自己购物车的项目才能购买 */
		$where_user_id = $this->visitor->get('user_id') ? " AND cart.user_id=" . $this->visitor->get('user_id') : '';
		$cart_model =& m('cart');
		$cart_items = $cart_model->find(array(
		'conditions'    => 'session_id = \'' . SESS_ID . "'" . $where_user_id ,
		'fields'        => 'this.*,store.store_name,store.im_qq,store.im_ww',
		'join'          => 'belongs_to_store',
		'order'    => 'goods_id DESC, spec_id DESC',
		));
		if (empty($cart_items))
		{
			return $carts;
		}
		$kinds = array();
		$price_list = array();
		foreach ($cart_items as $item)
		{
			/* 小计 */
			$item['subtotal']   = $item['price'] * $item['quantity'];

			/* 以店铺ID为索引 */
			empty($item['goods_image']) && $item['goods_image'] = Conf::get('default_goods_image');
			$carts[$item['store_id']]['store_name'] = $item['store_name'];

			if($item['price_type'] == 1)//按产品数量报价
			{
				//取得商品优惠价格列表
				$volumeprice_model   =& m('volumeprice');
				$price_list   = $volumeprice_model->get_infos($item['goods_id']);
				foreach($price_list as $key=>$val)
				{
					$price_list[$key]['min_number'] = $val['volume_number'];
					if(count($price_list)>1 && $key !=(count($price_list)-1))
					{
						$price_list[$key]['max_number'] = $price_list[$key+1]['volume_number']-1;
					}

				}
				$item['price_list']    =   $price_list;

			}

			$carts[$item['store_id']]['amount']     += $item['subtotal'];   //各店铺的总金额
			$carts[$item['store_id']]['quantity']   += $item['quantity'];   //各店铺的总数量
			//$kinds[$item['store_id']][$item['goods_id']] = 1;

			$carts[$item['store_id']]['goods'][]    = $item;
		}

		/*foreach ($carts as $_store_id => $cart)
		{
		$carts[$_store_id]['kinds'] =   count(array_keys($kinds[$_store_id]));  //各店铺的商品种类数
		}*/

		return $carts;
	}

	//更新购物车，AJAX更新
	function Ajaxupdate()
	{

		$spec_id  = isset($_GET['spec_id']) ? intval($_GET['spec_id']) : 0;
		$quantity = isset($_GET['quantity'])? intval($_GET['quantity']): 0;
		if (!$spec_id || !$quantity)
		{
			/* 不合法的请求 */
			$this->json_error('no_such_spec');
			return;
		}

		/* 判断库存是否足够 */
		$model_spec =& m('goodsspec');
		$spec_info  =  $model_spec->get($spec_id);
		if (empty($spec_info))
		{
			/* 没有该规格 */
			$this->json_error('no_such_spec');
			return;
		}

		if ($quantity > $spec_info['stock'])
		{
			/* 数量有限 */
			$this->json_error('no_enough_goods');
			return;
		}

		/* 修改数量 */
		$where = "spec_id={$spec_id} AND session_id='" . SESS_ID . "'";
		$model_cart =& m('cart');

		/* 获取购物车中的信息，用于获取产品ID及报价方式 */
		$cart_spec_info = $model_cart->get($where);
		if (empty($cart_spec_info))
		{
			/* 并没有添加该商品到购物车 */
			$this->json_error('no_such_spec');
			return;
		}

		$goods_id = $cart_spec_info['goods_id'];
		$goods_price_type  = $cart_spec_info['price_type'];//产品报价方式

		/* 修改数量 */
		$model_cart->edit($where, array(
		'quantity'  =>  $quantity,
		));

		/*如果是按数量报价的时候获取价格区间更新购物车里面的价格*/
		if($goods_price_type == 1)
		{
			$this->_update_cart_goods_price($goods_id);
		}

		/* 返回JSON结果 */
		//$cart_status = $this->_get_cart_status();
		$this->json_result('','update_item_successed');

	}
	//删除产品
	function Ajaxdel()
	{
		$rec_data = str_replace('\\', '', $_POST['rec_data']);
		$arr=json_decode($rec_data,true);

		if($arr['type']==='single')//单个移除
		{
			$rec_id=intval($arr['contents']);  //单个rec_id
			if(empty($rec_id))
			{
				$data=array('done'=>false,'msg'=>'参数错误');
				echo json_encode($data);
				die();
			}

			$where = "rec_id={$rec_id} AND session_id='" . SESS_ID . "'";
			$model_cart =& m('cart');

			/* 获取购物车中的信息，用于获取产品ID及报价方式 */
			$cart_spec_info = $model_cart->get($where);
			if (empty($cart_spec_info))
			{
				/* 并没有添加该商品到购物车 */
				$this->json_error('no_such_spec');
				return;
			}

			//从购物车中删除
			$droped_rows = $model_cart->drop('rec_id=' . $rec_id . ' AND session_id=\'' . SESS_ID . '\'');
			if (!$droped_rows)
			{
				$data=array('done'=>false,'msg'=>'服务器繁忙');
				echo json_encode($data);
				die();
			}

			$goods_id = $cart_spec_info['goods_id'];
			$goods_price_type  = $cart_spec_info['price_type'];//产品报价方式
			/*如果是按数量报价的时候获取价格区间更新购物车里面的价格*/
			if($goods_price_type == 1)
			{
				$this->_update_cart_goods_price($goods_id);
			}

			/* 返回JSON结果 */
			$this->json_result('','drop_item_successed');

		}
		elseif($arr['type']==='group') //删除所选
		{
			$store_id  = intval($arr['store_id']);
			$select    = intval($arr['select']);  //1表示店铺选择，0表示店铺没有选中，只是店铺下的部分产品选中
			$rec_ids   = implode(',',$arr['contents']);
			if(empty($rec_ids))
			{
				$data=array('done'=>false,'msg'=>'参数错误');
				echo json_encode($data);
				die();
			}
			$model_cart =& m('cart');
			$where = 'rec_id in (' . $rec_ids . ') AND session_id=\'' . SESS_ID . '\' and store_id = \'' . $store_id . '\'';



			if($select==1)//删除某店铺下的产品
			{
				/* 从购物车中删除 */
				$droped_rows = $model_cart->drop($where);
				if (!$droped_rows)
				{
					$data=array('done'=>false,'msg'=>'服务器繁忙');
					echo json_encode($data);
					die();
				}
				//重新获取价格给页面
				$cart_status = $this->_get_cart_status();

				/* 返回JSON结果 */
				$data=array('done'=>true,
				'msg'=>'OK',
				//'ordertotal'=>$cart_status['carts'][$store_id]['amount'],//店铺的总额
				'totalnum'  =>$cart_status['status']['quantity'],//购物车总数量
				'totalprice'=>$cart_status['status']['amount'],//购物车总金额
				//'newprice'=>$newprice
				);
				echo json_encode($data);
				die();

			}
			else //部分删除
			{

				$goods_info = $model_cart->find(array(
				'conditions'    => $where,
				'fields'        => 'this.goods_id,this.price_type,this.price',
				));
				if (empty($goods_info))
				{
					/* 并没有添加该商品到购物车 */
					$this->json_error('no_such_spec');
					return;
				}

				/* 从购物车中删除 */
				$droped_rows = $model_cart->drop($where);
				if (!$droped_rows)
				{
					$data=array('done'=>false,'msg'=>'服务器繁忙');
					echo json_encode($data);
					die();
				}

				$arr_goods_id = array();

				if(is_array($goods_info))
				{
					foreach($goods_info as $key=>$val)
					{
						if($val['price_type'] == 1) //是不是数量报价
						{
							$arr_goods_id[] = $val['goods_id'];
						}
					}
				}

				if(is_array($arr_goods_id))
				$result =  array_unique($arr_goods_id);//去除重复的goods_id，从而减小数据库的操作

				if(is_array($result))
				{
					foreach($result as $key=>$value)
					{
						$this->_update_cart_goods_price($value);//更新购物车中的价格
					}
				}

				//重新获取价格给页面
				$cart_status = $this->_get_cart_status();
				$newprice = array();
				foreach ($cart_status['carts'][$store_id]['goods']  as $key => $item )
				{
					if(in_array($item['goods_id'],$result))
					$newprice[$item['goods_id']] = $item['price'];
				}

				/* 返回JSON结果 */
				$data=array('done'=>true,
				'msg'=>'OK',
				'ordertotal'=>$cart_status['carts'][$store_id]['amount'],//店铺的总额
				'totalnum'  =>$cart_status['status']['quantity'],//购物车总数量
				'totalprice'=>$cart_status['status']['amount'],//购物车总金额
				'newprice'=>$newprice);
				echo json_encode($data);
				die();
			}


		}
		elseif($arr['type']==='all') //全部移除
		{
			/* 从购物车中删除 */
			$model_cart =& m('cart');
			$droped_rows = $model_cart->drop( 'session_id=\'' . SESS_ID . '\'');
			if (!$droped_rows)
			{
				$data=array('done'=>false,'msg'=>'服务器繁忙');
				echo json_encode($data);
				die();
			}
			$data=array('done'=>true);
			echo json_encode($data);
			die();
		}

	}

	function Ajaxfavorite()
	{
		$type=$_GET['type'];

		if($type==='single'){
			$goods_id=intval($_GET['goods_id']);
			//
			$result=array('done'=>true,'msg'=>'后台数据异常');
		}elseif($type==='all'){
			//
			$result=array('done'=>true,'msg'=>'后台数据异常');
		}
		echo json_encode($result);
	}
	//复选框
	function Ajaxbinding()
	{

		$type   = $_POST['type'];
		$status = intval($_POST['status']);//是否选中
		$rec_id = intval($_POST['rec_id']);
		$store_id = intval($_POST['store_id']);//店铺ID

		//print_r($_POST);die();

		if($type==='single') //单个选择
		{
			if(empty($rec_id) || empty($store_id))
			{
				$data=array('done'=>false,'msg'=>'参数错误');
				echo json_encode($data);
				die();
			}


			$where = "rec_id={$rec_id} AND session_id='" . SESS_ID . "'";
			$model_cart =& m('cart');

			/* 获取购物车中的信息，用于获取产品ID及报价方式 */
			$cart_spec_info = $model_cart->get($where);
			if (empty($cart_spec_info))
			{
				/* 并没有添加该商品到购物车 */
				$this->json_error('no_such_spec');
				return;
			}

			$goods_id = $cart_spec_info['goods_id'];
			$goods_price_type  = $cart_spec_info['price_type'];//产品报价方式
			/*如果是按数量报价的时候获取价格区间更新购物车里面的价格*/
			if($goods_price_type == 1)
			{
				$this->_update_cart_goods_price($goods_id);
			}

			/* 更改状态 */
			$model_cart->edit($where, array(
			'status'  =>  $status,
			));

			/* 返回JSON结果 */
			$data=array('done'=>true,'msg'=>'OK');
			echo json_encode($data);
			die();

		}
		elseif($type==='group')//某个店铺的选择
		{
			if(empty($store_id))
			{
				$data=array('done'=>false,'msg'=>'参数错误');
				echo json_encode($data);
				die();
			}


			$where = "session_id='" . SESS_ID . "' AND store_id={$store_id}";
			$model_cart =& m('cart');

			/* 更改状态 */
			$model_cart->edit($where, array(
			'status'  =>  $status,
			));

			/* 返回JSON结果 */
			$data=array('done'=>true,'msg'=>'OK');
			echo json_encode($data);
			die();

		}
		elseif($type==='all')//全选
		{

			/* 返回JSON结果 */

			$where = "session_id='" . SESS_ID . "' ";
			$model_cart =& m('cart');

			/* 更改状态 */
			$model_cart->edit($where, array(
			'status'  =>  $status,
			));

			$cart_status = $this->_get_cart_status();
			if($status == 1)//选中
			{

				foreach($cart_status['carts'] as $store_id=>$val)
				{
					$ordertotal[$store_id] = $val['amount'];
				}
				$totalnum    =  $cart_status['status']['quantity'];
				$totalprice  =  $cart_status['status']['amount'];

			}
			else
			{
				foreach($cart_status['carts'] as $store_id=>$val)
				{
					$ordertotal[$store_id] = 0;
				}
				$totalnum    =  0;
				$totalprice  =  0;
			}

			$data=array('done'=>true,
			'data'=>array(
			'ordertotal'  =>  $ordertotal,
			'totalnum'    =>  $totalnum,  //总商品数
			'totalprice'  =>  $totalprice//总价格
			));

			echo json_encode($data);
			die();
		}


	}
	//更新头部购物车，AJAX更新
	function Ajax_update_cart()
	{
		$cart_mod =& m('cart');
        $limit = intval($_GET['right_side']) > 0 ? intval($_GET['right_side']) : 5;
		$cart_data = $cart_mod->get_cart_top(SESS_ID,$this->visitor->get('user_id'),$limit);
		if($cart_data)
		{
			$this->json_result($cart_data,'your_cart_goods');
			return;
		}
		else
		{
			$this->json_error('cart_empty');
			return;
		}
	}
	//检查最小起批量
	function Ajaxcheckstock()
	{

		$rec_goods_data = str_replace('\\', '', $_POST['goods_ids']);
		$arr_params = json_decode($rec_goods_data, true);
		$arr_goods = $arr_params['goods_id'];
		$goods_ids = '';
		foreach ($arr_goods as $goods_id => $quantity)
		{
			$goods_ids .= intval($goods_id) . ',';
		}
		$goods_ids = trim($goods_ids, ',');
		$goods_mod = & m('goods');
		$goods_info = $goods_mod->findAll(array(
		'conditions' => 'goods_id in (' . $goods_ids . ')',
		'fields' => 'this.goods_id,this.start_stock,this.price_type',
		'include' => array('has_goodsspec' => array('fields' => 'gs.stock'))
		));

		//检查库存和起订量
		$result = $this->_check_stock($goods_info, $arr_params);
		//print_r($result);exit;
		if ($result['start_stock'] || $result['stock'])
		{
			$data = array('done' => false,
			'data' => $result);

			echo json_encode($data);
			die();
		}
		else
		{
			$data = array('done' => true);

			echo json_encode($data);
			die();
		}
	}

	//更新购物车中的其它产品规格的价格
	function _update_cart_goods_price($goods_id)
	{
		$goods_id = intval($goods_id);
		if($goods_id == 0)
		return false;

		$cart_model =& m('cart');
        $activity_goods_model =& m('activitygoods');
		$cart_totalnum = $cart_model->get_goods_totalnum(SESS_ID, $goods_id);//购物车包含商品的总数量
		if($cart_totalnum > 0)
		{
			$retail_price   = $cart_model->get_volume_price($goods_id,$cart_totalnum);//获取价格区间的价格
            $activity  = $activity_goods_model->_get_activity_goods($goods_id);//获取商品参与活动的数据
            $activity_goods = current($activity);
            if($activity_goods['discount_type'] == 1)
            {
                $price = $retail_price*$activity_goods['promote_discount'];
            }
            if($activity_goods['discount_type'] == 2)
            {
                $price = $activity_goods['promote_price'];
            }

            $goods_price = floatval($price) > 0 ? $price : $retail_price;
			/*更新适合条件商品的价格*/
			$cart_model->edit_cart_price($retail_price, $goods_price, " session_id='".SESS_ID."' AND goods_id = {$goods_id}");
		}
	}

	//检查库存和起订量
	function _check_stock($goods_items, $arr_params)
	{
		$result = array('start_stock' => array(), 'stock' => array());
		$arr_goods = $arr_params['goods_id'];
		$arr_spec = $arr_params['spec_id'];
		ksort($arr_goods);
		ksort($arr_spec);
		$k = 0;
		$i = 0;
		foreach ($goods_items as $goods_id => $val)
		{
			//检查库存
			$spec_status = false;
			foreach($val['gs'] as $spec_id => $spec){
				if(in_array($spec_id, array_keys($arr_spec))){
					if($spec['stock'] < $arr_spec[$spec_id]){
						$spec_status = true;
						$result['stock'][$i]['spec_id'] = $spec_id;
						$result['stock'][$i]['info'] = '此货品库存为' . $spec['stock'];
						$i++;
					}
				}
			}
			//检查起订量
			if(!$spec_status && $arr_goods[$goods_id] < $val['start_stock']){
				$result['start_stock'][$k]['goods_id'] = $goods_id;
				$result['start_stock'][$k]['info'] = '此货品最小起批量为' . $val['start_stock'];
				$k++;
			}
		}
		!$result['start_stock'] && $result['start_stock'] = 0;
		!$result['stock'] && $result['stock'] = 0;
		return $result;
	}

	//初始状态
	function _update_cart_status()
	{

		$cart_model =& m('cart');

		$where_user_id = $this->visitor->get('user_id') ? " AND user_id=" . $this->visitor->get('user_id') : '';

		$where =  'session_id = \'' . SESS_ID . "' AND status = 0 " . $where_user_id;
		$goods_info = $cart_model->find(array(
		'conditions'    => $where,
		'fields'        => 'this.goods_id,this.price_type',
		));

		$arr_goods_id = array();

		if(is_array($goods_info))
		{
			foreach($goods_info as $key=>$val)
			{
				if($val['price_type'] == 1) //是不是数量报价
				{
					$arr_goods_id[] = $val['goods_id'];
				}
			}


			if(is_array($arr_goods_id))
			$result =  array_unique($arr_goods_id);//去除重复的goods_id，从而减小数据库的操作

			if(is_array($result))
			{
				foreach($result as $key=>$value)
				{
					$this->_update_cart_goods_price($value);//更新购物车中的价格
				}
			}

			/* 更改状态 */
			$cart_model->edit($where, array(
			'status'  =>  1,
			));
		}


	}

	function update_cart_base_price()
	{

		$cart_model =& m('cart');
		$cart_items = $cart_model->find(array(
		'conditions'    => 'add_time > 0' ,
		'fields'        => 'this.spec_id',
		));

		//print_r($cart_items);die();

		foreach ($cart_items as $rec_id=>$val)
		{

			$spec_model =& m('goodsspec');

			$spec_info  =  $spec_model->get(array(
			'fields'        => 'g.price_type, g.clearing_price,gs.base_price',
			'conditions'    => $val['spec_id'],
			'join'          => 'belongs_to_goods',
			));

			$base_price = $spec_info['price_type']==1?$spec_info['clearing_price']:$spec_info['base_price'];//产品供货价

			/* 更改供货价*/
			$ret = $cart_model->edit('rec_id = '.$rec_id, array(
			'base_price'  => $base_price,
			));
			echo $ret."<br>";
		}


	}


	function update_order_base_price()
	{

		$order_goods_model =& m('ordergoods');
		$order_goods_items = $order_goods_model->find(array(
		'conditions'    => 'order_id > 0' ,
		'fields'        => 'this.spec_id',
		));

		//print_r($order_goods_items);die();

		foreach ($order_goods_items as $rec_id=>$val)
		{

			$spec_model =& m('goodsspec');

			$spec_info  =  $spec_model->get(array(
			'fields'        => 'g.price_type, g.clearing_price,gs.base_price',
			'conditions'    => $val['spec_id'],
			'join'          => 'belongs_to_goods',
			));

			$base_price = $spec_info['price_type']==1?$spec_info['clearing_price']:$spec_info['base_price'];//产品供货价

			/* 更改供货价*/
			$ret = $order_goods_model->edit('rec_id = '.$val['rec_id'], array(
			'base_price'  => $base_price,
			));
			echo $ret."<br>";
		}


	}


}

?>
